const Article = require('model/article')
const ApiError = require('errorException/apiError')
const utils = require('util/utils')
const redis = require('util/redis')
const config = require('@config/config')

// console.log(mongoose.model('zzz', {aa:{type:String},b:{type:Number}}))

module.exports = {
  /** 
   * 新增文章
   */
  create: async function(params) {
    let article = await Article.find({ 
      title: params.title
    })
    if (!article.length) {
      params.create_time = new Date().getTime()
      const result = await Article.create(params)
      return result
    }
    throw new ApiError('ar.HasExist')
  },

  /** 
   * 获取列表
   */
  findList: async function(params) {
    const skip = (Number(params.page) - 1) * Number(params.per_page)
    // console.log(params, skip)
    const filterArr = ['title', 'type', 'create_time']
    const data = await filterParams(filterArr, params)
    const articles = await Article.find(data).sort({ _id: -1 }).skip(skip).limit(Number(params.per_page))
    const total = await Article.find(data).estimatedDocumentCount()
    if (total && total > 0) {
      return {
        list: articles,
        pagination: {
          page: 1,
          prev: 1,
          total: total
        }
      }
    }
    throw new ApiError('ar.nodata')
  },

  /** 
   * @description: 更新文章
   */
  update: async function(params) {
    const article = await findArticle(params)
    if (article) {
      const filterArr = ['title', 'type', 'avatar', 'content']
      const data = await filterParams(filterArr, params)
      await Article.update({ _id: params.id }, { $set: data })
      return Article.findOne({ _id: params.id })
    }
    throw new ApiError('ar.notFinddata')
  },

  /** 
   * @description: 删除文章
   */
  delete: async function(params) {
    const article = await findArticle(params)
    if (article) {
      await Article.deleteOne({ _id: params.id })
      return { is_delete: true }
    } else {
      return { is_delete: flase }
    }
  }
}

/**  
 * @description: 查找单个文章
 */
const findArticle = async function(params) {
  return await Article.findOne({ _id: params.id })
}

/** 
 * @description: 过滤undefined字段
 */
const filterParams = async function(filterArr, params) {
  const data = {}
  for (let item in params) {
    if (item && filterArr.includes(item)) {
      data[item] = params[item]
    }
  }
  return data
}